//
//  DYMainRightVC.m
//  PrivatePhoto
//
//  Created by PrivatePhoto Team on 2021.
//  Copyright © 2021年 PrivatePhoto Team. All rights reserved.
//

#import "DYMainRightVC.h"
#import "BaseWebViewController.h"
#import "UIViewController+ZYSliderViewController.h"
#import "ZYSliderViewController.h"
#import "PBSubscribeViewController.h"
@interface DYMainRightVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, weak) UIButton *tipBtn;
@property (nonatomic, weak) UILabel *tipLabel;
@property (nonatomic, strong) NSArray *dataArray;
@end

@implementation DYMainRightVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configSubView];
    [self configData];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleVipTransactionEvent)
                                                 name:@"kVipDueDateChanded"
                                               object:nil];
}

- (void)configSubView{
//    
//    self.leftItem.hidden = YES;
//    self.gk_navBackgroundColor = [UIColor colorWithHexString:@"EDF4FF"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"EDF4FF"];
    self.tableView.frame = CGRectMake(kScreenWidth/3, 0, kScreenWidth*2/3, 140);
    [self.view addSubview:self.tableView];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 60)];
    self.tableView.tableHeaderView = headerView;
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.font = [UIFont boldSystemFontOfSize:15];
    tipLabel.textColor = [UIColor blackColor];
    tipLabel.textAlignment = NSTextAlignmentLeft;
    tipLabel.text = @"三天后过期";
    [headerView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_equalTo(headerView.mas_centerY);
        make.right.mas_offset(15);
    }];
  
    self.tipLabel = tipLabel;
    [self handleVipTransactionEvent];
}

- (void)configData{
    self.dataArray = @[@"服务条款",@"隐私政策"];//,@"恢复购买"
    [self.tableView reloadData];
}

- (void)handleVipTransactionEvent{
    NSString *tip = @"";
    if (kUserManager.userManager.isSubscribe) {
//        NSString *isVipDueDate = [kIAPHelper judgeTimeByStartAndEndTime:kUserManager.userManager.vipDueDate];
//        if ([isVipDueDate isEqualToString:@"过期"]) {
//
//            tip = @"恢复购买";
//            RAUserManager *userManager = kUserManager.userManager;
//            userManager.isSubscribe = NO;
//            userManager.vipDueDate = @"";
//
//            if ([kUserManager.userManager.auto_renew_status isEqualToString:@"1"]) {
//                //过期 但是还是处于订阅中 则证明有自动续订
//                //点击自动续费成功 打点
//            }
//            [userManager saveUserData:userManager];
//
//        } else if ([isVipDueDate isEqualToString:@"到期"]) {
//            //点击自动续费成功 打点
//            tip = @"自动订阅";
//        } else {
//            //未到期
//            NSString *deadTime = [kIAPHelper timeByStartTime:kUserManager.userManager.vipDueDate];
//            tip = [NSString stringWithFormat:@"您的订阅将在 %@ 到期",deadTime];
//
//        }
    }else{
        tip = @"开始三天免费使用";
    }

    self.tipLabel.text = tip;
    [kIAPHelper addTransactionObserver];
}


#pragma make --- tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    UILabel *titleLabel = [cell.contentView viewWithTag:indexPath.row];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (!titleLabel) {
        titleLabel = [[UILabel alloc] init];
        titleLabel.frame = CGRectMake(15, 8, 120, 28);
        [cell.contentView addSubview:titleLabel];
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.tag = indexPath.row;
        titleLabel.font = [UIFont systemFontOfSize:15];
    }
    titleLabel.text = self.dataArray[indexPath.row];
   
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[self sliderViewController] hideLeft];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *title = self.dataArray[indexPath.row];
//    if ([title isEqualToString:@"恢复购买"]) {
//        [self resumePurchaseEvent];
//        return;
//    }
    [self gotoBaseWebViewController:title];
    
}

- (void)gotoBaseWebViewController:(NSString *)title {
    BaseWebViewController *vc = [BaseWebViewController new];
    if ([title isEqualToString:@"服务条款"]) {
        vc.url = @"http://clean.ufit.work/policy-service.html";
    } else if ([title isEqualToString:@"隐私政策"]) {
        vc.url = @"http://clean.ufit.work/policy-privacy.html";
    }
    vc.webTitle = title;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)btnDidClick:(UIButton *)sender{
    if (kUserManager.userManager.isSubscribe) {
//        NSString *isVipDueDate = [kIAPHelper judgeTimeByStartAndEndTime:kUserManager.userManager.vipDueDate];
//        if ([isVipDueDate isEqualToString:@"过期"]) {
//            [self resumePurchaseEvent];
//        } else if ([isVipDueDate isEqualToString:@"到期"]) {
//            //点击自动续费成功 打点
//           
//        } else {
//            //未到期
//        }
    }else{
        [self startPurchseEvent];
    }
}

//购买

- (void)startPurchseEvent{
  
    PBSubscribeViewController *vc = [[PBSubscribeViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
    
    
}

//恢复购买
- (void)resumePurchaseEvent{

    [SVProgressHUD showWithStatus:@"恢复中..."];
    //恢复
    [kIAPHelper restorePurchasesWithCompleteHandle:^(IAPPurchType type, NSDictionary *dict) {
        if (type == IAPPurchVerSuccess || type == IAPPurchSuccess) {
            
            [SVProgressHUD dismiss];
            
            RAUserManager *userManager = kUserManager.userManager;

            NSArray *pending_renewal_info = dict[@"pending_renewal_info"];
            NSDictionary *latest_renewal_dic;
            if (pending_renewal_info.count > 0) {
                latest_renewal_dic = pending_renewal_info[pending_renewal_info.count - 1];
            }
            
            if (latest_renewal_dic) {
                //auto_renew_status 为0, 说明已经关闭订阅.
                NSString *auto_renew_status = latest_renewal_dic[@"auto_renew_status"];//是否开启订阅
                userManager.auto_renew_status = auto_renew_status;
                
            }
            
            NSArray *latest_receipt_ary = dict[@"latest_receipt_info"];
            
            NSDictionary *latest_receipt_dic;
            if (latest_receipt_ary.count > 0) {
                latest_receipt_dic = latest_receipt_ary[latest_receipt_ary.count - 1];
            }
            
            if (latest_receipt_dic) {
                NSString *expires_date_ms = latest_receipt_dic[@"expires_date_ms"];//过期时间
                NSString *product_id = latest_receipt_dic[@"product_id"];//产品id
                                
                if ([product_id containsString:@"18"]) {
                    //年费
                    //userManager.memberType = 2;
                    
                    
                    
                } else if ([product_id containsString:@"73"]) {
                    //月费
                    //userManager.memberType = 1;
                    
                    
                } else {
                    //周费
                    //userManager.memberType = 0;
                    
                    if (latest_receipt_ary.count == 1) {
                        //第一次订阅 并且是年费 则是免费试用
                        userManager.isFree = YES;
                    } else {
                        userManager.isFree = NO;
                    }
                }
                
                userManager.isSubscribe = YES;
                
                if (expires_date_ms.length >= 10) {
                    NSInteger date = [[expires_date_ms substringToIndex:10] integerValue];
                    userManager.vipDueDate = [NSDate time_timestampToString:date];
                }
                [userManager saveUserData:userManager];
        
                //关闭
                [self dismissViewControllerAnimated:YES completion:nil];
                
                kAppDelegate.isClose = YES;
                [kApplicationManager setupWindow:kAppDelegate.window];
            }
        } else {
           [SVProgressHUD dismiss];
        }
    }];
}

#pragma mark --- setter/getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 44;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _tableView.delaysContentTouches = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.scrollEnabled = NO;
        _tableView.tableFooterView = [[UIView alloc] init];
      
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
        
    }
    
    return _tableView;
}


@end
